import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import styles from './TeacherManagement.module.css';


const API_BASE = 'http://localhost:3001/api';

type TeacherStatus = 'active' | 'inactive';
type CourseStatus = 'upcoming' | 'ongoing' | 'completed';

interface Teacher {
  id: number;
  name: string;
  gender?: string;
  birthDate?: string;
  idCard?: string;
  phone: string;
  email: string;
  department: string;
  title: string;
  major?: string;
  course?: string;
  status: TeacherStatus;
  hireDate: string;
}

interface Course {
  id: number;
  name: string;
  code: string;
  teacher: string;
  students: number;
  duration: string;
  status: CourseStatus;
  credit?: number;
  hours?: number;
  teacherId?: number | null;
  department?: string;
  semester?: string;
  createdAt?: string;
  updatedAt?: string;
}

interface ClassItem {
  id: number;
  className: string;
  lecturer: string;
  counselor: string;
  department: string;
  classroom?: string;
  studentCount: number;
  students: any[];
}

interface TeacherDetail extends Teacher {
  classes: ClassItem[];
  currentClasses: ClassItem[];
  pastClasses: ClassItem[];
  classCount: number;
  currentClassCount: number;
  pastClassCount: number;
}

const TeacherManagement: React.FC = () => {
  const { t } = useTranslation('teacher');
  const { t: tCommon } = useTranslation('common');
  const { t: tStudent } = useTranslation('student');
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState<'teachers' | 'courses'>('teachers');
  const [teachers, setTeachers] = useState<Teacher[]>([]);
  const [courses, setCourses] = useState<Course[]>([]);
  const [isTeacherModalOpen, setIsTeacherModalOpen] = useState(false);
  const [isCourseModalOpen, setIsCourseModalOpen] = useState(false);
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
  const [teacherDetail, setTeacherDetail] = useState<TeacherDetail | null>(null);
  const [isLoadingDetail, setIsLoadingDetail] = useState(false);
  const [editingTeacher, setEditingTeacher] = useState<Teacher | null>(null);
  const [editingCourse, setEditingCourse] = useState<Course | null>(null);
  const [courseSearchTerm, setCourseSearchTerm] = useState('');
  const [currentUser, setCurrentUser] = useState<any>(null);
  const [isAdmin, setIsAdmin] = useState(false);

  useEffect(() => {
    // 获取当前用户信息
    const userStr = localStorage.getItem('user');
    if (userStr) {
      try {
        const user = JSON.parse(userStr);
        setCurrentUser(user);
        // 检查是否是管理员（从role字段判断）
        setIsAdmin(user.role === 'admin');
      } catch (error) {
        console.error('解析用户信息失败:', error);
      }
    }
  }, []);

  useEffect(() => {
    const loadData = async () => {
      try {
        const token = localStorage.getItem('accessToken') || localStorage.getItem('token');

        // 加载教师数据
        const teachersResponse = await fetch(`${API_BASE}/teachers`, {
          headers: token ? { 'Authorization': `Bearer ${token}` } : {}
        });
        if (teachersResponse.ok) {
          const responseData = await teachersResponse.json();
          const teachersData = responseData.data || responseData || [];
          if (Array.isArray(teachersData)) {
            setTeachers(teachersData);
          } else {
            console.error('教师数据不是数组:', teachersData);
            setTeachers([]);
          }
        } else {
          console.error('获取教师数据失败，状态码:', teachersResponse.status);
          setTeachers([]);
        }

        // 加载课程数据
        const coursesResponse = await fetch(`${API_BASE}/courses`, {
          headers: token ? { 'Authorization': `Bearer ${token}` } : {}
        });
        if (coursesResponse.ok) {
          const responseData = await coursesResponse.json();
          const coursesData = responseData.data || responseData || [];
          if (Array.isArray(coursesData)) {
            setCourses(coursesData);
          } else {
            console.error('课程数据不是数组:', coursesData);
            setCourses([]);
          }
        } else {
          console.error('获取课程数据失败，状态码:', coursesResponse.status);
          setCourses([]);
        }
      } catch (error) {
        console.error('加载数据失败:', error);
      }
    }; // 这里为 async loadData 的声明和结束
    loadData();
  }, []); // useEffect 闭合

  // 课程搜索过滤
  const filteredCourses = (courses || []).filter(course => {
    const searchTerm = courseSearchTerm.toLowerCase();
    return (
      (course.name && course.name.toLowerCase().includes(searchTerm)) ||
      (course.code && course.code.toLowerCase().includes(searchTerm)) ||
      (course.teacher && course.teacher.toLowerCase().includes(searchTerm))
    );
  });

  // 课程管理功能
  const handleAddCourse = () => {
    setEditingCourse(null);
    setIsCourseModalOpen(true);
  };

  const handleEditCourse = (course: Course) => {
    setEditingCourse(course);
    setIsCourseModalOpen(true);
  };

  const handleDeleteCourse = async (id: number) => {
    if (window.confirm(t('confirmDeleteCourse'))) {
      try {
        const response = await fetch(`${API_BASE}/courses/${id}`, {
          method: 'DELETE',
        });

        if (response.ok) {
          // 使用函数式更新确保获取最新的状态
          setCourses(prevCourses => prevCourses.filter(course => course.id !== id));
        } else {
          throw new Error('删除失败');
        }
      } catch (error) {
        console.error('删除课程失败:', error);
        alert(error instanceof Error ? `删除失败: ${error.message}` : '删除失败，请重试');
      }
    }
  };

  const handleSaveCourse = async (formData: Omit<Course, 'id'>) => {
    try {
      let response;
      if (editingCourse) {
        // 更新课程
        response = await fetch(`${API_BASE}/courses/${editingCourse.id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(formData),
        });
      } else {
        // 新增课程
        response = await fetch(`${API_BASE}/courses`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(formData),
        });
      }

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '操作失败');
      }

      const responseData = await response.json();
      // 确保正确获取数据，后端返回的是{success: true, data: {...}}格式
      const result = responseData.data || responseData;

      // 使用函数式更新确保获取最新的状态
      if (editingCourse) {
        setCourses(prevCourses =>
          prevCourses.map(course =>
            course.id === editingCourse.id ? result : course
          )
        );
      } else {
        setCourses(prevCourses => [...prevCourses, result]);
      }

      // 先重置状态，然后关闭模态框，确保状态同步
      setEditingCourse(null);
      setIsCourseModalOpen(false);
    } catch (error) {
      console.error('保存课程失败:', error);
      alert(error instanceof Error ? `操作失败: ${error.message}` : '操作失败，请重试');
    }
  };

  // 教师管理功能
  const handleAddTeacher = () => {
    setEditingTeacher(null);
    setIsTeacherModalOpen(true);
  };

  const handleEditTeacher = (teacher: Teacher) => {
    setEditingTeacher(teacher);
    setIsTeacherModalOpen(true);
  };

  // 检查是否可以编辑/删除教师（管理员可以，教师只能编辑自己）
  const canManageTeacher = (teacher: Teacher): boolean => {
    if (isAdmin) return true;
    if (!currentUser || !currentUser.phone) return false;
    return currentUser.phone === teacher.phone;
  };

  const handleDeleteTeacher = async (id: number) => {
    if (window.confirm('确定要删除这位老师吗？')) {
      try {
        const token = localStorage.getItem('accessToken') || localStorage.getItem('token');
        const response = await fetch(`${API_BASE}/teachers/${id}`, {
          method: 'DELETE',
          headers: token ? { 'Authorization': `Bearer ${token}` } : {}
        });

        if (response.ok) {
          // 使用函数式更新确保获取最新的状态
          setTeachers(prevTeachers => prevTeachers.filter(teacher => teacher.id !== id));
        } else {
          throw new Error('删除失败');
        }
      } catch (error) {
        console.error('删除失败:', error);
        alert(error instanceof Error ? `删除失败: ${error.message}` : '删除失败，请重试');
      }
    }
  };

  // 查看教师详情
  const handleViewDetail = async (teacher: Teacher) => {
    setIsLoadingDetail(true);
    setIsDetailModalOpen(true);
    setTeacherDetail(null);
    
    try {
      const response = await fetch(`${API_BASE}/teachers/${teacher.id}`);
      if (!response.ok) {
        throw new Error('获取详情失败');
      }
      
      const responseData = await response.json();
      const detail = responseData.data || responseData;
      setTeacherDetail(detail as TeacherDetail);
    } catch (error) {
      console.error('获取教师详情失败:', error);
      alert(error instanceof Error ? `获取失败: ${error.message}` : '获取失败，请重试');
      setIsDetailModalOpen(false);
    } finally {
      setIsLoadingDetail(false);
    }
  };

  // 跳转到班级管理页面
  const handleGoToClass = (className: string) => {
    navigate(`/admin/students/classes?className=${encodeURIComponent(className)}`);
  };


  const handleSaveTeacher = async (formData: Omit<Teacher, 'id' | 'hireDate'>) => {
    try {
      const token = localStorage.getItem('accessToken') || localStorage.getItem('token');
      const headers: Record<string, string> = {
        'Content-Type': 'application/json',
      };
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }

      let response;
      if (editingTeacher) {
        response = await fetch(`${API_BASE}/teachers/${editingTeacher.id}`, {
          method: 'PUT',
          headers,
          body: JSON.stringify(formData),
        });
      } else {
        response = await fetch(`${API_BASE}/teachers`, {
          method: 'POST',
          headers,
          body: JSON.stringify(formData),
        });
      }

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '操作失败');
      }

      const responseData = await response.json();
      // 确保正确获取数据，后端返回的是{success: true, data: {...}}格式
      const result = responseData.data || responseData;

      // 使用函数式更新确保获取最新的状态
      if (editingTeacher) {
        setTeachers(prevTeachers =>
          prevTeachers.map(teacher =>
            teacher.id === editingTeacher.id ? result : teacher
          )
        );
      } else {
        setTeachers(prevTeachers => [...prevTeachers, result]);
      }

      // 先重置状态，然后关闭模态框，确保状态同步
      setEditingTeacher(null);
      setIsTeacherModalOpen(false);
    } catch (error) {
      console.error('保存失败:', error);
      alert(error instanceof Error ? `操作失败: ${error.message}` : '操作失败，请重试');
    }
  };

  return (
    <div className={styles.teacherManagement}>
      <div className={styles.pageHeader}>
        <h2>{t('title')}</h2>
        <div className={styles.headerActions}>
          {activeTab === 'teachers' && isAdmin && (
            <button className={styles.btnPrimary} onClick={handleAddTeacher}>
              {t('addTeacher')}
              {t('addTeacher')}
            </button>
          )}
          {activeTab === 'courses' && (
            <button className={styles.btnPrimary} onClick={handleAddCourse}>
              {t('addCourse')}
              {t('addCourse')}
            </button>
          )}
        </div>
      </div>

      {/* 标签页 */}
      <div className={styles.tabs}>
        <button
          className={`${styles.tab} ${activeTab === 'teachers' ? styles.tabActive : ''}`}
          onClick={() => setActiveTab('teachers')}
        >
          {t('teacherManagement')}
        </button>
        <button
          className={`${styles.tab} ${activeTab === 'courses' ? styles.tabActive : ''}`}
          onClick={() => setActiveTab('courses')}
        >
          {t('courseManagement')}
        </button>
      </div>

      {/* 老师管理 */}
      {activeTab === 'teachers' && (
        <div className={styles.teachersSection}>
          <div className={styles.searchBox}>
            <input type="text" placeholder="搜索老师姓名、邮箱或部门..." />
          </div>

          <div className={styles.teachersTable}>
            <table>
              <thead>
                <tr>
                  <th>ID</th>
                  <th>{t('name')}</th>
                  <th>{t('email')}</th>
                  <th>{t('phone')}</th>
                  <th>{t('department')}</th>
                  <th>{t('title')}</th>
                  <th>{t('status')}</th>
                  <th>{t('joinDate')}</th>
                  <th>{t('operation')}</th>
                </tr>
              </thead>
              <tbody>
                {teachers.map(teacher => (
                  <tr key={`teacher-${teacher.id}`}>
                    <td>{teacher.id}</td>
                    <td className={styles.nameCell}>{teacher.name}</td>
                    <td className={styles.emailCell}>{teacher.email}</td>
                    <td>{teacher.phone}</td>
                    <td>{teacher.department}</td>
                    <td>{teacher.title}</td>
                    <td>
                      <span
                        className={`${styles.status} ${teacher.status === 'active' ? styles.statusActive : styles.statusInactive
                          }`}
                      >
                        {teacher.status === 'active' ? t('common:activated') : t('common:deactivated')}
                      </span>
                    </td>
                    <td>{teacher.hireDate}</td>
                    <td>
                      <div className={styles.actionButtons}>
                        <button className={styles.btnDetail} onClick={() => handleViewDetail(teacher)}>
                          {t('viewDetail')}
                        </button>
                        <button className={styles.btnEdit} onClick={() => handleEditTeacher(teacher)}>
                          {t('common:edit')}
                        </button>
                        <button className={styles.btnDelete} onClick={() => handleDeleteTeacher(teacher.id)}>
                          {t('common:delete')}
                        </button>
                        {canManageTeacher(teacher) && (
                          <button className={styles.btnEdit} onClick={() => handleEditTeacher(teacher)}>
                            {t('common:edit')}
                          </button>
                        )}
                        {isAdmin && (
                          <button className={styles.btnDelete} onClick={() => handleDeleteTeacher(teacher.id)}>
                            {t('common:delete')}
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* 课程管理 */}
      {activeTab === 'courses' && (
        <div className={styles.coursesSection}>
          <div className={styles.coursesStats}>
            <div className={styles.statItem}>
              <h3>总课程</h3>
              <div className={styles.statValue}>{courses.length}</div>
            </div>
            <div className={styles.statItem}>
              <h3>{tCommon('ongoing')}</h3>
              <div className={styles.statValue}>
                {courses.filter(c => c.status === 'ongoing').length}
              </div>
            </div>
            <div className={styles.statItem}>
              <h3>{tCommon('completed')}</h3>
              <div className={styles.statValue}>
                {courses.filter(c => c.status === 'completed').length}
              </div>
            </div>
            <div className={styles.statItem}>
              <h3>{tCommon('upcoming')}</h3>
              <div className={styles.statValue}>
                {courses.filter(c => c.status === 'upcoming').length}
              </div>
            </div>
          </div>

          <div className={styles.searchBox}>
            <input
              type="text"
              placeholder={t('searchPlaceholder')}
              value={courseSearchTerm}
              onChange={e => setCourseSearchTerm(e.target.value)}
            />
          </div>

          <div className={styles.coursesTable}>
            <table>
              <thead>
                <tr>
                  <th>{t('courseCode')}</th>
                  <th>{t('courseName')}</th>
                  <th>{t('teacher')}</th>
                  <th>{t('students')}</th>
                  <th>{t('duration')}</th>
                  <th>{t('status')}</th>
                  <th>{t('operation')}</th>
                </tr>
              </thead>
              <tbody>
                {filteredCourses.map(course => (
                  <tr key={`course-${course.id}`}>
                    <td className={styles.codeCell}>{course.code}</td>
                    <td className={styles.nameCell}>{course.name}</td>
                    <td>{course.teacher}</td>
                    <td>{course.students}</td>
                    <td>{course.duration}</td>
                    <td>
                      <span
                        className={`${styles.courseStatus} ${course.status === 'ongoing'
                          ? styles.courseStatusOngoing
                          : course.status === 'completed'
                            ? styles.courseStatusCompleted
                            : styles.courseStatusUpcoming
                          }`}
                      >
                        {course.status === 'ongoing'
                          ? tCommon('ongoing')
                          : course.status === 'completed'
                            ? tCommon('completed')
                            : tCommon('upcoming')}
                      </span>
                    </td>
                    <td>
                      <div className={styles.actionButtons}>
                        <button className={styles.btnEdit} onClick={() => handleEditCourse(course)}>
                          {t('common:edit')}
                        </button>
                        <button className={styles.btnDelete} onClick={() => handleDeleteCourse(course.id)}>
                          {t('common:delete')}
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* 老师模态框 */}
      {isTeacherModalOpen && (
        <TeacherModal
          teacher={editingTeacher}
          onSave={handleSaveTeacher}
          onClose={() => {
            setIsTeacherModalOpen(false);
            setEditingTeacher(null);
          }}
        />
      )}

      {/* 课程模态框 */}
      {isCourseModalOpen && (
        <CourseModal
          course={editingCourse}
          teachers={teachers}
          onSave={handleSaveCourse}
          onClose={() => {
            setIsCourseModalOpen(false);
            setEditingCourse(null);
          }}
        />
      )}

      {/* 教师详情模态框 */}
      {isDetailModalOpen && (
        <TeacherDetailModal
          teacherDetail={teacherDetail}
          isLoading={isLoadingDetail}
          onClose={() => {
            setIsDetailModalOpen(false);
            setTeacherDetail(null);
          }}
          onGoToClass={handleGoToClass}
        />
      )}
    </div>
  );
};

// 教师模态框组件
interface TeacherModalProps {
  teacher: Teacher | null;
  onSave: (formData: Omit<Teacher, 'id' | 'hireDate'>) => void;
  onClose: () => void;
}

const TeacherModal: React.FC<TeacherModalProps> = ({ teacher, onSave, onClose }) => {
  const { t } = useTranslation('teacher');
  const { t: tCommon } = useTranslation('common');

  // 初始化表单数据
  const [formData, setFormData] = useState({
    name: teacher?.name || '',
    gender: teacher?.gender || '',
    birthDate: teacher?.birthDate || '',
    idCard: teacher?.idCard || '',
    phone: teacher?.phone || '',
    email: teacher?.email || '',
    department: teacher?.department || '',
    title: teacher?.title || '',
    major: teacher?.major || '',
    course: teacher?.course || '',
    status: teacher?.status || 'active'
  });

  // 处理输入变化
  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  // 处理表单提交
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave(formData);
  };

  return (
    <div className={styles.modalOverlay}>
      <div className={styles.modal}>
        <div className={styles.modalHeader}>
          <h3>{teacher ? t('editTeacher') : t('addTeacher')}</h3>
          <button className={styles.closeBtn} onClick={onClose}>×</button>
        </div>

        <form onSubmit={handleSubmit}>
          <div className={styles.formGroup}>
            <label>{t('name')}</label>
            <input
              type="text"
              value={formData.name}
              onChange={(e) => handleInputChange('name', e.target.value)}
              required
            />
          </div>

          <div className={styles.formGroup}>
            <label>{t('email')}</label>
            <input
              type="email"
              value={formData.email}
              onChange={(e) => handleInputChange('email', e.target.value)}
              required
            />
          </div>

          <div className={styles.formGroup}>
            <label>{t('phone')}</label>
            <input
              type="text"
              value={formData.phone}
              onChange={(e) => handleInputChange('phone', e.target.value)}
              required
            />
          </div>

          <div className={styles.formGroup}>
            <label>{t('department')}</label>
            <input
              type="text"
              value={formData.department}
              onChange={(e) => handleInputChange('department', e.target.value)}
              required
            />
          </div>

          <div className={styles.formGroup}>
            <label>{t('title')}</label>
            <input
              type="text"
              value={formData.title}
              onChange={(e) => handleInputChange('title', e.target.value)}
              required
            />
          </div>

          <div className={styles.formGroup}>
            <label>{t('status')}</label>
            <select
              value={formData.status}
              onChange={(e) => handleInputChange('status', e.target.value)}
            >
              <option value="active">{tCommon('activated')}</option>
              <option value="inactive">{tCommon('deactivated')}</option>
            </select>
          </div>

          <div className={styles.modalActions}>
            <button type="button" onClick={onClose}>
              {tCommon('cancel')}
            </button>
            <button type="submit">
              {teacher ? tCommon('update') : tCommon('create')}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

// 课程模态框组件
interface CourseModalProps {
  course: Course | null;
  teachers: Teacher[];
  onSave: (formData: Omit<Course, 'id'>) => void;
  onClose: () => void;
}

const CourseModal: React.FC<CourseModalProps> = ({ course, teachers, onSave, onClose }) => {
  const { t } = useTranslation('teacher');
  const { t: tCommon } = useTranslation('common');

  // 初始化表单数据
  const [formData, setFormData] = useState({
    name: course?.name || '',
    code: course?.code || '',
    teacher: course?.teacher || '',
    students: course?.students || 0,
    duration: course?.duration || '',
    status: course?.status || 'upcoming'
  });

  // 处理输入变化
  const handleInputChange = (field: string, value: string | number) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  // 处理表单提交
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave(formData);
  };

  return (
    <div className={styles.modalOverlay}>
      <div className={styles.modal}>
        <div className={styles.modalHeader}>
          <h3>{course ? t('editCourse') : t('addCourse')}</h3>
          <button className={styles.closeBtn} onClick={onClose}>×</button>
        </div>

        <form onSubmit={handleSubmit}>
          <div className={styles.formGroup}>
            <label>{t('courseName')}</label>
            <input
              type="text"
              value={formData.name}
              onChange={(e) => handleInputChange('name', e.target.value)}
              required
            />
          </div>

          <div className={styles.formGroup}>
            <label>{t('courseCode')}</label>
            <input
              type="text"
              value={formData.code}
              onChange={(e) => handleInputChange('code', e.target.value)}
              required
            />
          </div>

          <div className={styles.formGroup}>
            <label>{t('teacher')}</label>
            <select
              value={formData.teacher}
              onChange={(e) => handleInputChange('teacher', e.target.value)}
              required
            >
              <option value="">请选择教师</option>
              {teachers.map(teacher => (
                <option key={teacher.id} value={teacher.name}>{teacher.name}</option>
              ))}
            </select>
          </div>

          <div className={styles.formGroup}>
            <label>{t('students')}</label>
            <input
              type="number"
              value={formData.students}
              onChange={(e) => handleInputChange('students', parseInt(e.target.value) || 0)}
              min="0"
              required
            />
          </div>

          <div className={styles.formGroup}>
            <label>{t('duration')}</label>
            <input
              type="text"
              value={formData.duration}
              onChange={(e) => handleInputChange('duration', e.target.value)}
              placeholder="例如: 16周"
              required
            />
          </div>

          <div className={styles.formGroup}>
            <label>{t('status')}</label>
            <select
              value={formData.status}
              onChange={(e) => handleInputChange('status', e.target.value)}
            >
              <option value="upcoming">{tCommon('upcoming')}</option>
              <option value="ongoing">{tCommon('ongoing')}</option>
              <option value="completed">{tCommon('completed')}</option>
            </select>
          </div>

          <div className={styles.modalActions}>
            <button type="button" onClick={onClose}>
              {tCommon('cancel')}
            </button>
            <button type="submit">
              {course ? tCommon('update') : tCommon('create')}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

// 教师详情模态框组件
interface TeacherDetailModalProps {
  teacherDetail: TeacherDetail | null;
  isLoading: boolean;
  onClose: () => void;
  onGoToClass: (className: string) => void;
  onViewStudents?: (classItem: ClassItem) => void;
  showClassStudents?: boolean;
  selectedClassStudents?: any[];
  selectedClassName?: string;
  onBackFromStudents?: () => void;
}

const TeacherDetailModal: React.FC<TeacherDetailModalProps> = ({
  teacherDetail,
  isLoading,
  onClose,
  onGoToClass,
  onViewStudents,
  showClassStudents,
  selectedClassStudents,
  selectedClassName,
  onBackFromStudents
}) => {
  const { t } = useTranslation('teacher');
  const { t: tCommon } = useTranslation('common');
  const { t: tStudent } = useTranslation('student');

  // 如果显示学生列表
  if (showClassStudents && selectedClassStudents && selectedClassName) {
    return (
      <div className={styles.modalOverlay} onClick={onClose}>
        <div className={styles.modal} onClick={(e) => e.stopPropagation()} style={{ maxWidth: '900px' }}>
          <div className={styles.modalHeader}>
            <h3>{t('classStudents')} - {selectedClassName}</h3>
            <button className={styles.closeBtn} onClick={onClose}>×</button>
          </div>
          <div style={{ padding: '1.5rem', maxHeight: '70vh', overflowY: 'auto' }}>
            {selectedClassStudents.length > 0 ? (
              <div className={styles.studentsList}>
                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                  <thead>
                    <tr>
                      <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid #e5e7eb', background: '#f8fafc', fontWeight: 600 }}>{tStudent('studentId')}</th>
                      <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid #e5e7eb', background: '#f8fafc', fontWeight: 600 }}>{tStudent('name')}</th>
                      <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid #e5e7eb', background: '#f8fafc', fontWeight: 600 }}>{tStudent('gender')}</th>
                      <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid #e5e7eb', background: '#f8fafc', fontWeight: 600 }}>{tStudent('phone')}</th>
                      <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid #e5e7eb', background: '#f8fafc', fontWeight: 600 }}>{tStudent('college')}</th>
                      <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid #e5e7eb', background: '#f8fafc', fontWeight: 600 }}>{tStudent('status')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {selectedClassStudents.map((student: any) => (
                      <tr key={student.id || student.studentId}>
                        <td style={{ padding: '0.75rem', borderBottom: '1px solid #e5e7eb' }}>{student.studentId}</td>
                        <td style={{ padding: '0.75rem', borderBottom: '1px solid #e5e7eb', fontWeight: 500 }}>{student.name}</td>
                        <td style={{ padding: '0.75rem', borderBottom: '1px solid #e5e7eb' }}>{student.gender || '-'}</td>
                        <td style={{ padding: '0.75rem', borderBottom: '1px solid #e5e7eb' }}>{student.phone || '-'}</td>
                        <td style={{ padding: '0.75rem', borderBottom: '1px solid #e5e7eb' }}>{student.college || '-'}</td>
                        <td style={{ padding: '0.75rem', borderBottom: '1px solid #e5e7eb' }}>
                          <span style={{
                            padding: '0.25rem 0.75rem',
                            borderRadius: '12px',
                            fontSize: '0.875rem',
                            fontWeight: 500,
                            background: student.status === 'active' ? '#d1fae5' : student.status === 'suspended' ? '#fee2e2' : '#e0e7ff',
                            color: student.status === 'active' ? '#065f46' : student.status === 'suspended' ? '#991b1b' : '#3730a3'
                          }}>
                            {student.status === 'active' ? tStudent('active') : student.status === 'suspended' ? tStudent('onLeave') : student.status === 'graduated' ? tStudent('graduated') : student.status || '-'}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <div style={{ textAlign: 'center', padding: '2rem', color: '#64748b' }}>
                {t('noStudents')}
              </div>
            )}
          </div>
          <div className={styles.modalActions}>
            <button type="button" onClick={onBackFromStudents || onClose}>
              {t('back')}
            </button>
            <button type="button" onClick={onClose}>
              {tCommon('close')}
            </button>
          </div>
        </div>
      </div>
    );
  }

  // 显示教师详情
  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div className={styles.modal} onClick={(e) => e.stopPropagation()} style={{ maxWidth: '900px' }}>
        <div className={styles.modalHeader}>
          <h3>{t('teacherDetail')}</h3>
          <button className={styles.closeBtn} onClick={onClose}>×</button>
        </div>
        <div style={{ padding: '1.5rem', maxHeight: '70vh', overflowY: 'auto' }}>
          {isLoading ? (
            <div style={{ textAlign: 'center', padding: '2rem' }}>加载中...</div>
          ) : teacherDetail ? (
            <>
              {/* 基本信息 */}
              <div className={styles.detailSection}>
                <h4 style={{ marginBottom: '1rem', color: '#1e293b', fontSize: '1.1rem', fontWeight: 600 }}>
                  {t('basicInfo')}
                </h4>
                <div className={styles.detailGrid}>
                  <div className={styles.detailItem}>
                    <label>{t('name')}:</label>
                    <span>{teacherDetail.name}</span>
                  </div>
                  <div className={styles.detailItem}>
                    <label>{t('email')}:</label>
                    <span>{teacherDetail.email || '-'}</span>
                  </div>
                  <div className={styles.detailItem}>
                    <label>{t('phone')}:</label>
                    <span>{teacherDetail.phone || '-'}</span>
                  </div>
                  <div className={styles.detailItem}>
                    <label>{t('department')}:</label>
                    <span>{teacherDetail.department || '-'}</span>
                  </div>
                  <div className={styles.detailItem}>
                    <label>{t('title')}:</label>
                    <span>{teacherDetail.title || '-'}</span>
                  </div>
                  <div className={styles.detailItem}>
                    <label>{t('joinDate')}:</label>
                    <span>{teacherDetail.hireDate || '-'}</span>
                  </div>
                  <div className={styles.detailItem}>
                    <label>{t('status')}:</label>
                    <span className={teacherDetail.status === 'active' ? styles.statusActive : styles.statusInactive}>
                      {teacherDetail.status === 'active' ? tCommon('activated') : tCommon('deactivated')}
                    </span>
                  </div>
                </div>
              </div>

              {/* 现在的班级 */}
              <div className={styles.detailSection} style={{ marginTop: '2rem' }}>
                <h4 style={{ marginBottom: '1rem', color: '#1e293b', fontSize: '1.1rem', fontWeight: 600 }}>
                  {t('currentClasses')} ({teacherDetail.currentClassCount || 0})
                </h4>
                {teacherDetail.currentClasses && teacherDetail.currentClasses.length > 0 ? (
                  <div className={styles.classesList}>
                    {teacherDetail.currentClasses.map((classItem) => (
                      <div 
                        key={classItem.id} 
                        className={styles.classCard}
                        onClick={() => {
                          onGoToClass(classItem.className);
                          onClose();
                        }}
                        style={{ cursor: 'pointer' }}
                      >
                        <div className={styles.classCardHeader}>
                          <h5 style={{ margin: 0, fontSize: '1rem', fontWeight: 600 }}>{classItem.className}</h5>
                          <div className={styles.classCardInfo}>
                            <div className={styles.classInfoItem}>
                              <span className={styles.classInfoLabel}>{t('department')}:</span>
                              <span>{classItem.department || '-'}</span>
                            </div>
                            <div className={styles.classInfoItem}>
                              <span className={styles.classInfoLabel}>{t('counselor')}:</span>
                              <span>{classItem.counselor || '-'}</span>
                            </div>
                            {classItem.classroom && (
                              <div className={styles.classInfoItem}>
                                <span className={styles.classInfoLabel}>{t('classroom')}:</span>
                                <span>{classItem.classroom}</span>
                              </div>
                            )}
                            <div className={styles.classInfoItem}>
                              <span className={styles.classInfoLabel}>{tStudent('students')}:</span>
                              <span>{classItem.studentCount || 0}</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div style={{ textAlign: 'center', padding: '2rem', color: '#64748b' }}>
                    {t('noClasses')}
                  </div>
                )}
              </div>

              {/* 带过的班级 */}
              {teacherDetail.pastClasses && teacherDetail.pastClasses.length > 0 && (
                <div className={styles.detailSection} style={{ marginTop: '2rem' }}>
                  <h4 style={{ marginBottom: '1rem', color: '#1e293b', fontSize: '1.1rem', fontWeight: 600 }}>
                    {t('pastClasses')} ({teacherDetail.pastClassCount || 0})
                  </h4>
                  <div className={styles.classesList}>
                    {teacherDetail.pastClasses.map((classItem) => (
                      <div 
                        key={classItem.id} 
                        className={styles.classCard}
                        onClick={() => {
                          onGoToClass(classItem.className);
                          onClose();
                        }}
                        style={{ cursor: 'pointer' }}
                      >
                        <div className={styles.classCardHeader}>
                          <h5 style={{ margin: 0, fontSize: '1rem', fontWeight: 600 }}>{classItem.className}</h5>
                          <div className={styles.classCardInfo}>
                            <div className={styles.classInfoItem}>
                              <span className={styles.classInfoLabel}>{t('department')}:</span>
                              <span>{classItem.department || '-'}</span>
                            </div>
                            <div className={styles.classInfoItem}>
                              <span className={styles.classInfoLabel}>{t('counselor')}:</span>
                              <span>{classItem.counselor || '-'}</span>
                            </div>
                            <div className={styles.classInfoItem}>
                              <span className={styles.classInfoLabel}>{tStudent('students')}:</span>
                              <span>{classItem.studentCount || 0}</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </>
          ) : (
            <div style={{ textAlign: 'center', padding: '2rem', color: '#64748b' }}>
              暂无数据
            </div>
          )}
        </div>
        <div className={styles.modalActions}>
          <button type="button" onClick={onClose}>
            {tCommon('close')}
          </button>
        </div>
      </div>
    </div>
  );
};

export default TeacherManagement;
